//
//  HNSH_ChatGroupViewController.m
//  HNSH_SingleProject
//
//  Created by 李宇廷 on 2023/2/17.
//

#import "HNSH_ChatGroupViewController.h"

//view
#import "HNSH_ChatGroupNavView.h"
#import "HNSH_TextMessageCell.h"
#import "HNSH_VoiceMessageCell.h"
#import "HNSH_HQVoiceMessageCell.h"
#import "HNSH_ImageMessageCell.h"
#import "HNSH_FileMessageCell.h"
#import "HNSH_GIFMessageCell.h"

#import "HNSH_SendRedContent.h"
#import "HNSH_SendRedMessageCell.h"
#import "HNSH_OpenContent.h"
#import "HNSH_OpenRedMessageCell.h"

#import "HNSH_ChatOpenRedAlert.h"

//model
#import "HNSH_GroupInfoModel.h"
#import "HNSH_ChatOpenRedInfoModel.h"

//vc
#import "HNSH_GroupChatInfoViewController.h"            //聊天设置
#import "HNSH_ChatFriendDetailViewController.h"         //朋友信息
#import "HNSH_ChatSendRedViewController.h"              //创建红包页面
#import "HNSH_ChatOpenRedDetailViewController.h"        //拆红包详情

@interface HNSH_ChatGroupViewController ()

/* chatNavView */
@property (nonatomic, strong) HNSH_ChatGroupNavView *chatNavView;

/** 群里信息 */
@property (nonatomic, strong) HNSH_GroupInfoUserModel * groupModel;
@end

@implementation HNSH_ChatGroupViewController

//MARK: Cycle Methods
- (void)viewDidLoad{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F6F6F6"];
    
    NSLog(@"encode_id ==> %@",self.targetId);
    
    [self addAllViews];
    
    [self addObserver];
    
    [self registerCell];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.hidden = YES;
    
    [self loadGroupInfo];
    
    [self getDisStatus];
    
    [HNSH_RYTools loadMembersWithGroupId:self.targetId];
}

- (void)addAllViews{
    self.enableUnreadMentionedIcon = YES;
    self.enableNewComingMessageIcon = YES;
    self.conversationMessageCollectionView.frame = CGRectMake(0, kNavBarAndStatusBarHeight, kScreenWidth, kScreenHeight - kNavBarAndStatusBarHeight - kBottomSafeHeight - 49);
    [self.view addSubview:self.chatNavView];
    //
    [self.chatSessionInputBarControl.pluginBoardView updateItemWithTag:1001 normalImage:[UIImage imageNamed:@"chat_pic"] highlightedImage:[UIImage imageNamed:@"chat_pic"] title:@"相册"];
    [self.chatSessionInputBarControl.pluginBoardView updateItemWithTag:1002 normalImage:[UIImage imageNamed:@"chat_xj"] highlightedImage:[UIImage imageNamed:@"chat_xj"] title:@"拍摄"];
//    [self.chatSessionInputBarControl.pluginBoardView removeItemWithTag:1003];
//    [self.chatSessionInputBarControl.pluginBoardView insertItem:[UIImage imageNamed:@"chat_wenjian"] highlightedImage:[UIImage imageNamed:@"chat_wenjian"] title:@"文件" tag:1006];
//    [self.chatSessionInputBarControl.pluginBoardView insertItem:[UIImage imageNamed:@"chat_shouchang"] highlightedImage:[UIImage imageNamed:@"chat_shouchang"] title:@"收藏" tag:2002];
    [self.chatSessionInputBarControl.pluginBoardView insertItem:[UIImage imageNamed:@"chat_hongbao"] highlightedImage:[UIImage imageNamed:@"chat_hongbao"] title:@"红包" tag:2003];
}

- (void)pluginBoardView:(RCPluginBoardView *)pluginBoardView clickedItemWithTag:(NSInteger)tag{
    [super pluginBoardView:pluginBoardView clickedItemWithTag:tag];
    
//    if (tag == 2001) {
//        [self order];
//    }
//    if (tag == 2002) {//收藏
//        NYChatCollectionViewController *vc = [[NYChatCollectionViewController alloc]init];
//        vc.isHaveNav = YES;
//        vc.groupModel = self.groupModel;
//        [[CFBHelper getTopViewController].navigationController pushViewController:vc animated:YES];
//    }
    if (tag == 2003) {//发送红包
        NSLog(@"发送红包");
        HNSH_ChatSendRedViewController *vc = [[HNSH_ChatSendRedViewController alloc]init];
        vc.targetId = self.targetId;
        vc.memberCount = self.groupModel.member_count;
        vc.sendRedBlock = ^(NSString * _Nonnull count, NSString * _Nonnull money, NSString * _Nonnull des, NSString * _Nonnull redId) {
            HNSH_SendRedContent *content = [HNSH_SendRedContent objectWithCount:count price:money des:des];
            content.recordId = redId;
            content.extra = @"status";
            RCUserInfo * userInfo = [[RCUserInfo alloc] init];
            userInfo.userId = [ST_UserManager shareInstance].rcUser.uid;
            userInfo.name = [ST_UserManager shareInstance].rcUser.name;
            userInfo.portraitUri = [ST_UserManager shareInstance].rcUser.portrait;
            content.senderUserInfo = userInfo;

            RCMessage *msg = [[RCMessage alloc] initWithType:self.conversationType targetId:self.targetId direction:(MessageDirection_SEND) content:content];
            msg.canIncludeExpansion = YES;
            msg.expansionDic = @{@"status":@"0",@"openIds":@""};
            __weak typeof(self) weakSelf = self;
            [RCIM.sharedRCIM sendMessage:msg pushContent:nil pushData:nil successBlock:^(RCMessage *successMessage) {
            } errorBlock:^(RCErrorCode nErrorCode, RCMessage *errorMessage) {

            }];

        };
        [[UIViewControllerHelper findCurrentShowingViewController].navigationController pushViewController:vc animated:YES];
    }
}

- (void)addObserver{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clear) name:@"kClearGroupMessage" object:nil];
}

- (void)clear{
    [[RCIMClient sharedRCIMClient] deleteMessages:ConversationType_GROUP targetId:self.targetId success:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.conversationDataRepository removeAllObjects];
            [self.conversationMessageCollectionView reloadData];
        });
        
    } error:^(RCErrorCode status) {
            
    }];
}

////MARK: 重写长按显示
//- (void)didLongTouchMessageCell:(RCMessageModel *)model inView:(UIView *)view {
//    NSArray *ary = [super getLongTouchMessageCellMenuList:model];
//    NSMutableArray *items = [NSMutableArray array];
//    for (UIMenuItem *item in ary) {
//        if ([item.title isEqualToString:@"复制"]) {
//            [items addObject:@(RXPopMenuItemCopy)];
//        }
//        if ([item.title isEqualToString:@"删除"]) {
//            [items addObject:@(RXPopMenuItemDelete)];
//        }
//        if ([item.title isEqualToString:@"撤回"]) {
//            [items addObject:@(RXPopMenuItemRevoke)];
//        }
//    }
//    [items addObject:@(RXPopMenuItemForward)];
//    [items addObject:@(RXPopMenuItemCollect)];
//
//    //群管理+群主可以撤回所有
//    if (self.groupModel.memberRole == 1 || self.groupModel.memberRole == 10) {
//        if (![items containsObject:@(RXPopMenuItemRevoke)]) {
//            [items insertObject:@(RXPopMenuItemRevoke) atIndex:1];
//        }
//    }
//
//    NSMutableArray * menuItems = [[NSMutableArray alloc] init];
//    for (id item in items) {
//        RXPopMenuItemType itemType = [item integerValue];
//        [menuItems addObject:[RXPopMenuItem itemWithType:itemType]];
//    }
//    RXPopMenu * menu = [RXPopMenu menuWithType:RXPopMenuBox];
//    [menu showBy:view withItems:menuItems];
//
//    menu.itemActions = ^(RXPopMenuItem *item) {
//        if (item.itemType == RXPopMenuItemCopy) {//复制
//            RCTextMessage *msg = (RCTextMessage *)model.content;
//            [UIPasteboard generalPasteboard].string = msg.content;
//            [MBProgressHUD showText:@"复制成功"];
//        }
//        if (item.itemType == RXPopMenuItemDelete) {//删除
//            [self deleteMessage:model];
//        }
//        if (item.itemType == RXPopMenuItemRevoke) {//撤回
//            [self recallMessage:model.messageId];
//        }
//        if (item.itemType == RXPopMenuItemForward) {//转发
//            NYForwardListViewController *vc = [[NYForwardListViewController alloc]init];
//            vc.msgModel = model;
//            [[CFBHelper getTopViewController].navigationController pushViewController:vc animated:YES];
//        }
//        if (item.itemType == RXPopMenuItemCollect) {//收藏
//            [NYChatForwardTools collectMsg:model groupId:self.targetId];
//        }
//    };
//    menu.menuHideDone = ^{
//    };
//}


//MARK: 获取免打扰状态
- (void)getDisStatus{
    [[RCIMClient sharedRCIMClient] getConversationNotificationStatus:ConversationType_GROUP targetId:self.targetId success:^(RCConversationNotificationStatus nStatus) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (nStatus == DO_NOT_DISTURB) {
                self.chatNavView.isDis = YES;
            } else {
                self.chatNavView.isDis = NO;
            }
        });
    } error:^(RCErrorCode status) {
        
    }];
}


//MARK: Custom Methods
- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)report{
    HNSH_GroupChatInfoViewController * vc = [HNSH_GroupChatInfoViewController new];
    vc.targetId = self.targetId;
    [self.navigationController pushViewController:vc animated:YES];
}

/** 注册自定义cell */
- (void)registerCell{
    //发送红包消息
    [self registerClass:HNSH_SendRedMessageCell.class forMessageClass:HNSH_SendRedContent.class];
    //打开红包消息
    [self registerClass:HNSH_OpenRedMessageCell.class forMessageClass:HNSH_OpenContent.class];
    [self registerClass:HNSH_TextMessageCell.class
        forMessageClass:RCTextMessage.class];
    [self registerClass:HNSH_VoiceMessageCell.class forMessageClass:RCVoiceMessage.class];
    [self registerClass:HNSH_HQVoiceMessageCell.class forMessageClass:RCHQVoiceMessage.class];
    [self registerClass:HNSH_ImageMessageCell.class forMessageClass:RCImageMessage.class];
    [self registerClass:HNSH_FileMessageCell.class
        forMessageClass:RCFileMessage.class];
    [self registerClass:HNSH_GIFMessageCell.class
        forMessageClass:RCGIFMessage.class];
    
}

- (void)sendMessageWithText:(NSString *)text{
    if (!text.length) {
        return;
    }
    NSString * extra = [NSString getExtraString];
    RCUserInfo * userInfo = [[RCUserInfo alloc] init];
    userInfo.userId = [ST_UserManager shareInstance].rcUser.uid;
    userInfo.name = [ST_UserManager shareInstance].rcUser.name;
    userInfo.portraitUri = [ST_UserManager shareInstance].rcUser.portrait;
    userInfo.extra = extra;
    RCTextMessage * message = [RCTextMessage messageWithContent:text];
    message.senderUserInfo = userInfo;
    [RCIM.sharedRCIM sendMessage:self.conversationType targetId:self.targetId content:message pushContent:nil pushData:nil success:^(long messageId) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
        });
    } error:^(RCErrorCode nErrorCode, long messageId) {
        
    }];
}

- (void)loadGroupInfo{
    [HNSH_ChatNetServer requestRongCloudGroupInfoWithGroupId:self.targetId success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            NSDictionary * data = responseObject.resultset;
            RCGroup * group = [[RCGroup alloc] init];
            group.groupId = data[@"encode_id"];
            NSString * displayName = data[@"display_name"];
            group.groupName = displayName.length ? displayName : data[@"name"];
            group.portraitUri = data[@"portrait_url"];
            [[RCIM sharedRCIM] refreshGroupInfoCache:group withGroupId:self.targetId];
            
            HNSH_GroupInfoUserModel * model = [HNSH_GroupInfoUserModel yy_modelWithDictionary:data];
            self.groupModel = model;
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

//- (void)showChooseUserViewController:(void (^)(RCUserInfo *selectedUserInfo))selectedBlock
//                              cancel:(void (^)(void))cancelBlock {
//    NYGroupRemindViewController *vc = [[NYGroupRemindViewController alloc]init];
//    vc.targetId = self.targetId;
//    vc.block = selectedBlock;
//    vc.memberRole = self.groupModel.memberRole;
//    [CFBHelper getTopViewController].modalPresentationStyle = UIModalPresentationFormSheet;
//    [[CFBHelper getTopViewController] presentViewController:vc animated:YES completion:nil];
//}

#pragma mark 修改文本消息中的超链接的颜色
- (void)willDisplayMessageCell:(RCMessageBaseCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    //修改头像
    if ([cell isKindOfClass:[RCMessageCell class]]) {
        RCMessageCell *msgCell = (RCMessageCell *)cell;
        UIImageView *portraitImageView= (UIImageView *)msgCell.portraitImageView;
        portraitImageView.image = [UIImage imageNamed:@"base_user_header_icon"];
    }
    //修改字体颜色
    if([cell isKindOfClass:[RCTextMessageCell class]]){
        RCTextMessageCell *txtCell = (RCTextMessageCell *)cell;
        txtCell.textLabel.attributeDictionary = @{@(NSTextCheckingTypeLink) :
                                                      @{NSForegroundColorAttributeName : [UIColor colorWithHexString:@"#576B94"]},
                                               @(NSTextCheckingTypePhoneNumber) :
                                                      @{NSForegroundColorAttributeName : [UIColor colorWithHexString:@"#576B94"]}};
        txtCell.textLabel.highlightedAttributeDictionary = @{@(NSTextCheckingTypeLink) :
                                                                 @{NSForegroundColorAttributeName : [UIColor colorWithHexString:@"#576B94"]},
                                                         @(NSTextCheckingTypePhoneNumber) :
                                                                 @{NSForegroundColorAttributeName : [UIColor colorWithHexString:@"#576B94"]}};
    }
}


#pragma mark - 用户点击回调
/** 点击头像 */
- (void)didTapCellPortrait:(NSString *)userId{
    if (![userId isEqualToString:[ST_UserManager shareInstance].rcUser.uid]) {
        HNSH_ChatFriendDetailViewController * vc = [HNSH_ChatFriendDetailViewController new];
        vc.rcUserId = userId;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

//自定义消息点击
- (void)didTapMessageCell:(RCMessageModel *)model {
    [super didTapMessageCell:model];
    
    if ([model.content isKindOfClass:[HNSH_SendRedContent class]]) {
        [self loadShowRedInfoWithModel:model];
    }
//    //
//    if ([model.content isKindOfClass:[DLSendOrderContent class]]) {
//        DLSendOrderContent * con = (DLSendOrderContent *)model.content;
//        if (con.type == 1) {
//            //同意
//            [self confirmOrderWithModel:model];
//        }
//        if (con.type == 2) {
//            //拒绝
//            [self rejectOrderWithModel:model];
//        }
//    }
}

#pragma mark 查看红包信息
- (void)loadShowRedInfoWithModel:(RCMessageModel *)model {
    HNSH_SendRedContent * content = (HNSH_SendRedContent *)model.content;
    [HNSH_ChatNetServer requestRongCloudRedPacketOpenInfoWithRedId:content.recordId success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            HNSH_ChatOpenRedInfoModel *redModel = [HNSH_ChatOpenRedInfoModel yy_modelWithDictionary:responseObject.resultset];


            //拆红包
            HNSH_ChatOpenRedAlert *alert = [[HNSH_ChatOpenRedAlert alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
            alert.redInfo = redModel;
            __weak __typeof(&*self)weakSelf = self;
            alert.openRedBlock = ^(HNSH_ChatOpenRedInfoModel * _Nonnull redInfo) {
                [weakSelf loadOpenRedWithRedInfo:redInfo msgModel:model];
            };
            [alert showView];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];

}

- (void)loadOpenRedWithRedInfo:(HNSH_ChatOpenRedInfoModel *)redInfo msgModel:(RCMessageModel *)model {
    
    [HNSH_ChatNetServer requestRongCloudRedPacketOpenWithRedId:redInfo.uid success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            RCMessage *oldMess = [[RCIMClient sharedRCIMClient] getMessageByUId:model.messageUId];
            dispatch_async(dispatch_get_main_queue(), ^{
                for (RCMessageModel *model in self.conversationDataRepository) {
                    if (model.messageId == oldMess.messageId) {
                        HNSH_SendRedContent *oldHongBao = (HNSH_SendRedContent *)model.content;
                        oldHongBao.status = 1;
                        model.content = oldHongBao;
                        oldMess.content = oldHongBao;

                    }
                }
                    NSLog(@"oldMess.expansionDic ==> %@",oldMess.expansionDic);
                    NSArray *ary = [oldMess.expansionDic[@"openIds"] componentsSeparatedByString:@","];
                    NSMutableArray *array = [NSMutableArray arrayWithArray:ary];
                    [array addObject:[ST_UserManager shareInstance].rcUser.uid];
                    NSString *openIds = [array componentsJoinedByString:@","];

                [[RCIMClient sharedRCIMClient] updateMessageExpansion:@{@"openIds":openIds} messageUId:oldMess.messageUId success:^{

                } error:^(RCErrorCode status) {

                }];
                [self.conversationMessageCollectionView reloadData];
            });
            HNSH_ChatOpenRedDetailViewController *vc = [[HNSH_ChatOpenRedDetailViewController alloc]init];
            vc.redId = redInfo.uid;
            [[UIViewControllerHelper findCurrentShowingViewController].navigationController pushViewController:vc animated:YES];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

- (RCMessageContent *)willSendMessage:(RCMessageContent *)messageContent{
    NSString * extra = [NSString getExtraString];
    RCUserInfo * userInfo = [[RCUserInfo alloc] init];
    userInfo.userId = [ST_UserManager shareInstance].rcUser.uid;
    userInfo.name = [ST_UserManager shareInstance].rcUser.name;
    userInfo.portraitUri = [ST_UserManager shareInstance].rcUser.portrait;
    userInfo.extra = extra;
    messageContent.senderUserInfo = userInfo;
    if (messageContent.mentionedInfo && messageContent.mentionedInfo.userIdList) {
        for (int i = 0; i < messageContent.mentionedInfo.userIdList.count; i++) {
            NSString *userId = messageContent.mentionedInfo.userIdList[i];
            if ([userId isEqualToString:@"All"]) {
                messageContent.mentionedInfo.type = RC_Mentioned_All;
                break;
            }
        }
    }
    return messageContent;
}

//- (void)inputTextView:(UITextView *)inputTextView
//    shouldChangeTextInRange:(NSRange)range
//      replacementText:(NSString *)text{
//    if (inputTextView.text.length > 100) {
//        inputTextView.text = [inputTextView.text substringToIndex:100];
//    }
//}

//MARK: Setter Methods
- (void)setGroupModel:(HNSH_GroupInfoUserModel *)groupModel{
    _groupModel = groupModel;
    
    NSString * title = groupModel.display_name.length ? groupModel.display_name : groupModel.name;
    self.chatNavView.title = [NSString stringWithFormat:@"%@(%ld/%ld)", title, groupModel.member_count, groupModel.max_member_count];
}

//MARK: Getter Methods
- (HNSH_ChatGroupNavView *)chatNavView{
    if (!_chatNavView) {
        _chatNavView = [[HNSH_ChatGroupNavView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kNavBarAndStatusBarHeight)];
        _chatNavView.title = self.title;
        
        WeakSelf(weakSelf);
        _chatNavView.backBlock = ^{
            [weakSelf back];
        };
        _chatNavView.reportBlock = ^{
            [weakSelf report];
        };
    }
    return _chatNavView;
}

@end
